#include <iostream>
#include <cstdarg>
#include <ctime>
#include <chrono>
#include "common_log.hpp"

#include <mutex>

std::mutex g_mutex;

void log_with_format(const char *prefix, const char *function, const int line, const char *fmt, ...) {
    std::lock_guard<std::mutex> lock(g_mutex);
    va_list args;
    va_start(args, fmt);

    va_list args_copy;
    va_copy(args_copy, args);
    const int length = vsnprintf(nullptr, 0, fmt, args_copy) + 1; // +1 for null terminator
    va_end(args_copy);

    const auto msg = new char[length];

    // 格式化字符串
    vsnprintf(msg, length, fmt, args);
    va_end(args);

    // 获取当前时间
    auto now = std::chrono::system_clock::now();
    std::time_t now_time_t = std::chrono::system_clock::to_time_t(now);
    char buffer[80];
    std::strftime(buffer, sizeof(buffer), "[%Y-%m-%d %H:%M:%S]", std::localtime(&now_time_t));

    // 打印格式化后的消息以及函数名和行号
    std::cout << buffer << prefix;
    std::cout << msg;
    std::cout << "][" << function << ":" << line << "]" << std::endl;

    // 释放分配的内存
    delete[] msg;
}
